import 'dart:async';
import 'dart:ui' as ui show Image;

import 'package:flutter/material.dart';

class ImageUtils {
  ImageUtils._();

  static Widget getImage(String assetName, double? width, double? height,
      {PathFormat pathFormat = PathFormat.normal,
      ImageFormat format = ImageFormat.png,
      BoxFit fit = BoxFit.scaleDown,
      Color? color,
      Key? key}) {
    return Image.asset(
      'assets/${pathFormat.value}$assetName.${format.value}',
      key: key,
      width: width,
      height: height,
      fit: fit,
      color: color,
    );
  }

  static Future<ui.Image?> loadImageByProvider(
    ImageProvider? provider, {
    ImageConfiguration config = ImageConfiguration.empty,
  }) async {
    if (provider == null) {
      return null;
    }
    Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调
    ImageStreamListener? listener;
    ImageStream stream = provider.resolve(config); //获取图片流
    listener = ImageStreamListener((ImageInfo frame, bool sync) {
      //监听
      final ui.Image image = frame.image;
      completer.complete(image); //完成
      if (listener != null) {
        stream.removeListener(listener); //移除监听
      }
    });
    stream.addListener(listener); //添加监听
    return completer.future; //返回
  }

  static ImageProvider getAssetImageProvider(String name,
      {PathFormat pathFormat = PathFormat.normal,
      ImageFormat format = ImageFormat.png}) {
    return AssetImage(getImgPath(name, pathFormat: pathFormat, format: format));
  }

  static AssetImage getAssetImage(String name,
      {PathFormat pathFormat = PathFormat.normal,
      ImageFormat format = ImageFormat.png}) {
    return AssetImage(getImgPath(name, pathFormat: pathFormat, format: format));
  }

  static String getImgPath(String name,
      {PathFormat pathFormat = PathFormat.normal,
      ImageFormat format = ImageFormat.png}) {
    return 'assets/${pathFormat.value}$name.${format.value}';
  }

  //获取圆角本地图片
  static ClipRRect getRoundImgPath(
      String assetName, double width, double height, double round,
      {PathFormat pathFormat = PathFormat.normal,
      ImageFormat format = ImageFormat.png}) {
    return ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(round)),
      child: Image.asset(
        'assets/${pathFormat.value}$assetName.${format.value}',
        width: width,
        height: height,
        fit: BoxFit.scaleDown,
      ),
    );
  }
}

enum ImageFormat { png, jpg, gif, webp }

enum PathFormat {
  normal,
  icon,
}

extension ImageFormatExtension on ImageFormat {
  String get value => ['png', 'jpg', 'gif', 'webp', 'svg'][index];
}

extension PathFormatExtension on PathFormat {
  String get value => [
        'images/',
        'icons/',
      ][index];
}
